package com.fy.springcloud.controller;

import com.fy.springcloud.feign.GoodsServiceFeign;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

@RestController
public class GoodsController {

//    private final static String GOODS_SERVICE_LIST_URL = "http://localhost:9001/goods/list";
    private final static String GOODS_SERVICE_LIST_URL = "http://springcloud-service-goods/goods/list";

    @Autowired
    private RestTemplate restTemplate;

    @Resource
    private GoodsServiceFeign goodsServiceFeign;

    @Autowired
    private HttpHeaders httpHeaders;

    @Value("${mysqldb.datasource.url:''}")
    private String databases;

    @GetMapping("/client/goods/list")
    public List<String> getGoodsList() {
        ResponseEntity<List<String>> response = restTemplate.exchange(GOODS_SERVICE_LIST_URL, HttpMethod.GET, null,
                new ParameterizedTypeReference<List<String>>() {
                });
        return response.getBody();
    }

    @GetMapping("/client/goods/list2")
    public List<String> getGoodsList2() {
        ResponseEntity<List<String>> response = restTemplate.exchange(GOODS_SERVICE_LIST_URL, HttpMethod.GET, new HttpEntity<>(httpHeaders),
                new ParameterizedTypeReference<List<String>>() {
                });
        return response.getBody();
    }

    @GetMapping("/feign/goods/list")
    public List<String> getFeignGoodsList() {
        return goodsServiceFeign.getGoodsList();
    }

    @GetMapping("/hystrix/goods/list")
    @HystrixCommand(fallbackMethod = "fallback")
    public List<String> getHystrixGoodsList() {
        // 1、服务超时会降级，hystrix默认超时时间是1秒
//        try {
//            Thread.sleep(2000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

        // 2、服务异常会降级
//        int i = 10 / 0;

        // 3、远程方法超时、异常、宕机也会降级
        return goodsServiceFeign.getGoodsList();
    }

    public List<String> fallback() {
        return Collections.singletonList("error");
    }


    @GetMapping("/feign/fallback/goods/list")
    public List<String> getFeignFallbackGoodsList() {
        return goodsServiceFeign.getGoodsList();
    }

    @GetMapping("/goods/databases")
    public String getGoodsDatabases() {
        return databases;
    }
}
